/**
 * 全局错误处理管理器
 * 用于在request.js中统一处理错误弹窗
 */
import { createApp, h } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import ErrorDialog from '@/components/common/ErrorDialog.vue'

class ErrorHandler {
  constructor() {
    this.errorDialogInstance = null
    this.container = null
    this.errorInfo = {
      topic: '错误详情',
      message: '错误描述：',
      data: null,
      timestamp: null,
      success: false
    }
  }

  /**
   * 初始化错误弹窗实例
   */
  initErrorDialog() {
    if (this.errorDialogInstance) {
      return
    }

    // 创建错误弹窗的容器
    this.container = document.createElement('div')
    document.body.appendChild(this.container)

    // 创建Vue应用实例，使用render函数而不是template
    const app = createApp({
      data() {
        return {
          showErrorDialog: false,
          errorInfo: {
            topic: '错误详情',
            message: '错误描述：',
            data: null,
            timestamp: null,
            success: false
          }
        }
      },
      methods: {
        showError(errorData) {
          this.errorInfo = { ...errorData }
          this.showErrorDialog = true
        },
        hideError() {
          this.showErrorDialog = false
        }
      },
      render() {
        return h(ErrorDialog, {
          modelValue: this.showErrorDialog,
          topic: this.errorInfo.topic,
          message: this.errorInfo.message,
          data: this.errorInfo.data,
          'onUpdate:modelValue': (value) => {
            this.showErrorDialog = value
          },
          onConfirm: this.hideError
        })
      }
    })

    // 注册Element Plus
    app.use(ElementPlus)
    
    this.errorDialogInstance = app.mount(this.container)
  }

  /**
   * 显示错误弹窗
   * @param {Object} errorData - 错误数据
   */
  showErrorDialog(errorData) {
    this.initErrorDialog()
    
    if (this.errorDialogInstance) {
      this.errorDialogInstance.showError(errorData)
    }
  }

  /**
   * 处理后端错误响应
   * @param {Object} response - 后端响应对象
   * @returns {boolean} 是否为code 499错误
   */
  handleErrorResponse(response) {
    if (response && response.code === 499) {
      const errorData = {
        topic: response.topic || '错误详情',
        message: response.message || '错误描述：',
        data: response.data || null,
        timestamp: response.timestamp || new Date().toLocaleString(),
        success: response.success || false
      }
      
      this.showErrorDialog(errorData)
      return true
    }
    return false
  }

  /**
   * 销毁错误弹窗实例
   */
  destroy() {
    if (this.errorDialogInstance) {
      this.errorDialogInstance.$destroy()
      this.errorDialogInstance = null
    }
    if (this.container) {
      document.body.removeChild(this.container)
      this.container = null
    }
  }
}

// 创建全局错误处理实例
const errorHandler = new ErrorHandler()

export default errorHandler
